package com.zone.core.helper

import android.content.Intent
import android.content.pm.PackageInfo
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import androidx.core.content.FileProvider
import com.zone.core.CoreApplication
import java.io.File

object ApkHelper {
    private val context = CoreApplication.coreApp


    //APK是否安装
    fun isInstalled(pkgName: String): Boolean {
        if (TextUtils.isEmpty(pkgName)) {
            return false
        }
        return try {
            val packageInfo = context.packageManager.getPackageInfo(pkgName, 0)
            packageInfo != null
        } catch (e: Exception) {
            false
        }
    }

    //获取包信息
    fun getPackageInfo(pkgName: String): PackageInfo? {
        return context.packageManager.getPackageInfo(pkgName, 0)
    }

    //安装apk
    fun installApk(file: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(
                FileProvider.getUriForFile(
                    context, context.packageName + ".fileProvider", file
                ), "application/vnd.android.package-archive"
            )
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        context.startActivity(intent)
    }
}